<?php

/**	
 *	social stream object
 *	
 *	module that renders and forms for adding streams as youtube,vimeo and the streams
 * 	the class is documented in the file itself. if you find any bugs help us out and report them. 
 * 	if you report a bug, make sure you give us enough information (include your code).
 *
 *	@author			pieter van peteghem <pieter@onedotonly.be>
 *
 *	@copyright		oneDot only <we@onedotonly.be>
 * 	@copyright		Copyright (c) 2010, oneDot only. All rights reserved.
 * 	@license		BSD License
 */


MOD_CONSTRUCT::req_mod( "text.form" );
class SocialStream extends MOD {


	/**
	 *	constructor
	 *	
	 *	add module vars and reference (multiple modules on 1 page are possible)	
	 *	@param		array ($vars)
	 */
	 
	function __construct( $vars ) {
		$this->_addvars( $vars );
		$this->_ref();
	}


	/**
	 * 	define output
	 *
	 *	this is the base for rendering the form at the frontend
	 *	while rendering the form css is added, an IE check is executed, javascript is added
	 *
	 *	@return		string - the form
	 *	@param		string (action)
	 *	@param		boolean (vars->iewarn)
	 */
	 
	public function output() {
		
		if( $this->action )
			$result = $this->{ "filter_" . $this->action }();

		$this->addclass( $this->action );
		
		if ( $result && is_array( $result ))
			$result = '<ul>' . implode( "\n", $result ) . '</ul>';
			
		if( $result )
			return $this->parse( $result ) . $this->render_js();
		
	}


	/**
	 * copy to own server
	 * @param	string	original source
	 * @param	string	destination
	 * @param	string	name
	 * @param	string 	extension
	 */

	private function copy_thumb( $source, $dest, $name, $extension = '.jpg' ) {
	
		$image 		= @file_get_contents( $source );
		$new_img 	= fopen ( $dest . $name . $extension, 'w');
		fwrite ( $new_img, $image );
		fclose ( $new_img ); 
		
		return $new_img;
	}
	/**
	 * render single movie
	 */
	function filter_single( $node, $link = false ) {
		global $DB, $Object;
		
			$stream = array_shift( $DB->filter_objects( 'social.stream', "ID = " . $node ));
			$stream_id = stripslashes( $stream->get( 'id' ));
			
			// check for ids or urls
			if( $stream->get( 'source' ) == 'youtube' && stristr( $stream_id, '?v' )) {
				$pos	= strpos( $stream_id, '?v' );
				$stream_id = substr( $stream_id, $pos + 3, 11 );

			} else if( $stream->get( 'source' ) == 'vimeo' && strlen( $stream_id ) > 12 ) {
				
				$stream_id = array_pop( explode( '/', $stream_id ));
			
			}
			// define variables, images...	
			if( $stream->get( 'source' ) == 'youtube' ) {
		
				if( !$DB->reference( 'social.stream', (int) $node, 'social.img', false, 'social' ) && $this->url_exists('http://gdata.youtube.com/feeds/api/videos/' . (string) $stream_id )) {
					$youtube = new Youtube();
		
					// get thumbnail
					$thumb 	= (object) $youtube->video_info( $stream_id, 'media$group' );
					$media 	= 'media$thumbnail'; 
					$thumb 	= $thumb->$media;
					$thumb	= $thumb[ 0 ]->url;
					
					$new_image	= $DB->set( 'social.img', array( 'active' => 1, 'meta' => array( 'raw' => $thumb, 'source' => 'youtube', 'id' => $stream_id )));
					$DB->query( "insert into glue_social ( `parenttype`, `parentid`, `objtype`, `objid`, `rank`) values 
						(" . $DB->type( 'social.stream' ) . ", " . (int) $node . ", " . $DB->type( 'social.img' ) . ", " . (int) $new_image . ", 5 )", 0 );
					
					$this->copy_thumb( $thumb, ROOT . ACCOUNT . '/www/DB/social/', (int) $new_image );
				} else {
				
					$images = $DB->reference( 'social.stream', (int) $node, 'social.img', false, 'social' );
					$thumb 	= '/public.img?id=' . array_pop( $images ) . '&social=1&sze=' . $this->vars->width . '.' . $this->vars->height;
				}
			
			}
			
			if( $stream->get( 'source' ) == 'vimeo') {
			
				if( !$DB->reference( 'social.stream', (int) $node, 'social.img', false, 'social' ) && $this->url_exists('http://vimeo.com/api/v2/video/' . $stream_id . '.xml')) {
					$vimeo  = new Vimeo();
					$info	= (object) $vimeo->video_info( $stream_id, array('thumbnail_large', 'thumbnail_small'));
					$thumb	= (( $this->vars->thumbs) ? $info->thumbnail_small : $info->thumbnail_large );

					$new_image	= $DB->set( 'social.img', array( 'active' => 1, 'meta' => array( 'raw' => $thumb, 'source' => 'vimeo', 'id' => $stream_id )));
					$DB->query( "insert into glue_social ( `parenttype`, `parentid`, `objtype`, `objid`, `rank`) values 
						(" . $DB->type( 'social.stream' ) . ", " . (int) $node . ", " . $DB->type( 'social.img' ) . ", " . (int) $new_image . ", 5 )", 0 );
					
					$this->copy_thumb( $thumb, ROOT . ACCOUNT . '/www/DB/social/', (int) $new_image );
				} else {
				
					$images = $DB->reference( 'social.stream', (int) $node, 'social.img', false, 'social' );
					$thumb 	= '/public.img?id=' . array_pop( $images ) . '&social=1&sze=' . $this->vars->width . '.' . $this->vars->height;
				}
			}
			
			// define output
			if( $link ) {
				$return[] = '<div style="position: relative; width:' . $this->vars->width . 'px; height:' . $this->vars->height . 'px;" class="thumb">';
				$return[] = '<a href="/' . $link . '?id=' . $Object->id . '&name=' . $Object->get( 'name' ) . '">';
				$return[] = '<img src="' . $thumb . '" />';
				$return[] = '</a></div>';
			
			} else {
				$return[] = '<div style="position: relative; background: url(' . $thumb . ') no-repeat center center; width:' . $this->vars->width . 'px; height:' . $this->vars->height . 'px;" class="thumb">';
					
				if( !$this->vars->thumbs ) {
					$return[] = '<div class="playIt" style="width:' . $this->vars->width . 'px; height:' . $this->vars->height . 'px;" id="' . $stream->get('ID') . '"></div>';
					$return[] = '</div>';
					$return[] = '<div style="position: relative; width:' . $this->vars->width . 'px; height:' . $this->vars->height . 'px;" class="stream hide">';
					$return[] = $this->render_movie( $stream_id, $stream->get('source'), $this->vars->width, $this->vars->height);
					$return[] = '</div>';
			
				} else {
					$return[] = '</div>';
				}
		
				$User = new USER( (int) $stream->get( 'creator' ));
				$return[] = '<span class="name">&nbsp;' . $stream->get( 'name' ) . '<i>' . $User->get( "fname" ) . '</i></span>';
			}
		
		
		return implode( "\n", $return );

		
	}
	
	
	/**
	 *	filter social stream
	 *	filter all social streams that are connected with an object
	 */
	 
	 private function filter_stream() {
	 	global $DB, $Object;
	 	
	 	if( $Object || $this->vars->ptype ) {
	 		
	 		// collect social streams connected to object
	 		$condt = (( $Object->id )? " parentid = " . $Object->id . " AND ": "" ) . (( $this->vars->personal )? " user = " . $_SESSION['uid'] . " AND ": "") . "active ORDER BY ID DESC" . (( $limit = $this->vars->limit)? " LIMIT " . $limit: "" );
	 		
	 		if( $streams = $DB->reference( $this->vars->ptype, $condt, "social.stream", false, 'social' )) {
				foreach( $streams as $stream ) {
									
					// define output
					$return[] = '<li class="movie" id="ref">';
					$return[] = $this->filter_single( $stream ) . '</li>';
				}
			} else {
			
				//$return[] = '<span class="empty">.empty</span>';
			}

	 	} else if( $vars->id && $vars->type ) {
	 		echo '<script type="text/javascript">console.log("bar")</script>';
	 	} else {
	 		echo '<script type="text/javascript">console.log("nothing")</script>';	
	 	}
	 	
		$this->js = "
			mod = new SocialStream();
			mod.prepstream();
		";
		
	 	return $return;
	 	
	 }
	 
	function filter_connected() {
		global $DB;
		
		//$CAL = new CALENDAR( "%d.%m" );

		if( $streams = $DB->filter_objects( 'social.stream' )) {
		
			foreach( $streams as $stream ) {
				$connect	= $DB->reference( $this->vars->ptype, false, 'social.stream', $stream->id, 'social' );
				
				if( $connect && $stream->get( 'creator' )) {
					
					$connecter	= new CALNODE( $this->vars->ptype, (int) array_pop( $connect ));
					//print_r( $connecter );
					$type		= $connecter->type;
					$Location	= ( $type == "cal.single" )? $connecter->loc : (( $type == "location" )? $connecter : false );
					$Bestemming	= ( $type == "cal.single" )? $connecter->obj : (( $type == "bestemming" )? $connecter : $Location->ref_object( "bestemming", 0 ));
					$Country	= ( $Bestemming )? $Bestemming->ref_object( "country", 0 ): false;
					$User		= new USER( (int) $stream->get( 'creator' ));

					$return[] = '<li class="movie">';
					$return[] = $this->filter_single( $stream->id );
					$return[] = '<div class="info">';
					$return[] = "<h1>{$connecter->get( 'name' )} ({$Location->get( 'name' )})</h1>";	
					$return[] = "<div class='subbar'>";
					$return[] = "<span class='date'>{$connecter->date( "%w d/m ", "- %w d/m" )}</span>";
					$return[] = "<span class='dest'><a href='{$Bestemming->uri()}'>{$Bestemming->get( 'name' )}</a>, ";
					$return[] = "<a href='{$Country->uri()}'>{$Country->get('name')}</a></span>";
					$return[] = "</div>";
					$return[] = '<p><b>Filmpje</b><br />' . $stream->get( 'name' ) . ' <span class="creator">' . $User->get( 'fname' ) . '</span>';
					$return[] = '<br /><br /><a href="/reizen/reisblog?id=' . $connecter->id . '" class="more">Voeg zelf een filmpje, afbeelding of verhaal	 toe!</a></p>';
					$return[] = '</div>';
					$return[] = '</li>';
				}
 			}
	 		
	 		$return[]	= '<span href="#" class="nav next">Volgende</span>';
	 		$return[]	= '<span href="#" class="nav prev">Vorige</span>';
		
			$return[] = '<li class="stable"></li>';
	 		
			$this->js = "
				mod = new SocialStream(" . json_encode( $this->vars ) . ");
				mod.prepstream();
				mod.splitter();
			";
		
		 	return $return;
		}
	}
	 
	 
	function filter_teaser() {
		global $Object, $DB;
		if( $Object && $Object->type == "cal.single" && $Object->get( 'date' ) < date( 'Y-m-d H:i:s' )) {
	 		
	 		// collect social streams connected to object
	 		$personal = false;
			if( $this->vars->personal || $_GET[ 'det' ] == 'me' )
				$personal = true;
	 		
	 		$condt = (( $Object->id )? " parentid = " . $Object->id . " AND ": "" ) . (( $personal )? " user = " . $_SESSION['uid'] . " AND ": "") . "active ORDER BY ID DESC" . (( $limit = $this->vars->limit)? " LIMIT " . $limit: "" );
	 		
	 		if( $streams = $DB->reference( (( $this->vars->ptype ) ?$this->vars->ptype : $Object->type ), $condt, "social.stream", false, 'social' )) {
				foreach( $streams as $stream ) {
				
					$return[] = '<li class="movie" id="ref">';
					$return[] = $this->filter_single( $stream, $this->vars->url ) . '</li>';
				}
			} else {
				$return[] = '<li class="movie empty" style="position: relative; min-height: 15px;" >';
				$return[] = '<a href="' . $this->vars->url . '?id=' . $Object->id . '&name=' . $Object->get( 'name' ) . '" style="display:block; width:' . $this->vars->width * 2 . 'px; height:' . $this->vars->height . 'px">';
				$return[] = '';
				$return[] = '</a></li>';
			
			}
		
			if( $this->vars->url ) {
				$return[] = '<li>';
				$return[] = '<a href="/' . $this->vars->url . '?id=' . $Object->id . '&name=' . $Object->get( 'name' ) . '" title="' . $Object->get( 'name' ) . '">' . $this->vars->urltext . '</a>';
				$return[] = '</li>';
	 		}
		
			$return[] = '<li class="stable">';
			if( $this->vars->url ) {
				$text = $this->unshift_content();
				$return[] = '<a class="more" href="/' . $this->vars->url . '?id=' . $Object->id . '&name=' . $Object->get( 'name' ) . '" title="' . $Object->get( 'name' ) . '">' . $text . '</a>';
	 		}
			$return[] = '</li>';
	 		
			$this->js = "
				mod = new SocialStream();
				mod.prepstream();
			";
		
		 	return $return;
		}
	 	
	}
	 
	 
	function filter_slideshow() {
		global $DB, $Object;
		
		$personal = false;
		if( $this->vars->personal || $_GET[ 'det' ] == 'me' )
			$personal = true;
	
		if( $this->vars->type == 'recent' )	
			$nodes = $DB->filter_objects( 'social.stream', 'active AND nameid != "..." ORDER BY ID DESC LIMIT ' . $this->vars->limit );
			
		else if( $Object && $this->vars->type = 'ref' )
			$nodes = $DB->reference( $Object->type, 'parentid = ' . (int) $Object->get( 'ID' ) . (( $personal )? ' && user = ' . $_SESSION['uid'] : '' ), 'social.stream', false, 'social' );
					
		// movies	
		$i = 0;
		if( $nodes ) {
		
			array_reverse( $nodes );
			$return[]	= '<ul id="movies" class="movies">';
			foreach ( $nodes as $node ){
				$return[] = '<li class="movie ' . (( $i == 0) ? 'active': 'hide' ) . '" id="ref' . $i . '">';
				$movie = $this->filter_single( $node );
				$return[] = $movie;
				$return[] = '</li>';
			
				$i++;
			}
			$return[] = '</ul>';
			
			// navigation
			$return[] = '<div class="navigation">';
			for( $i = 0; $i< count( $nodes); $i++ ) 
				$return[] = '<a href="#" onclick="return false;" class="navigate' . (( $i == 0 ) ? ' active' : '' ) . '" rel="' . $i . '">next</a>';
		
			$return[] = '</div>';
			
			$this->js = "
				mod = new SocialStream();
				mod.slideshow();
				mod.prepstream();
			";
			$return =  implode( "\n", $return );
		} else {
		
			$return[]	= '<ul id="movies" class="movies">';
			$return[] 	= '<li class="movie empty" style="position: relative;" >';
			$return[]	= '</li></ul>';
		}
		return $return;
	}
	
	
	/**
	 * 	check if url exists
	 *
	 *	@param		string
	 *	@return		int
	 */
	function url_exists($url) {
		@ $headers = get_headers($url);
    	return preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]);
	}  
	

	 

	/**
	 * 	get link of movie
	 *	@return		string (url of movie)
	 *	@param		int (id)
	 * 	@param		string (source)
	 */
	 
	function render_link( $id, $source ) {
	
		if ($source == 'youtube') {
			$url	= 'http://www.youtube.com/v/' . $id . '&hl=en_US&fs=1&';
		} else if ($source == 'vimeo') {
			$url	= 'http://vimeo.com/moogaloop.swf?clip_id=' . $id . '&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1"';
		}
		
		return $url;
	}
	
	
	/**
	 *	render movie
	 *	@return		string (stream object)
	 *	@param		int (id)
	 * 	@param		string (source)
	 *	@param		int (width)
	 *	@param		int (height)
	 */
	 
	function render_movie( $id, $source = 'youtube', $width = 480, $height = 385 ) {
	
		$url	= $this->render_link( $id, $source );
		
		$movie	= '<object width="' . $width . '" height="' . $height . '"><param name="movie" value="' . $url . '" />';
		$movie	.= '<param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" />';
		$movie	.= '<embed src="' . $url . '" type="application/x-shockwave-flash" 
			allowscriptaccess="always" allowfullscreen="true" width="' . $width . '" height="' . $height . '" /></object>';
			
		return $movie;
	}


}


/** 
 * YOUTUBE CLASS
 *
 * This can be used to communicate with youtube (http://youtube.com)
 *
 * This is only the beginning of a youtube class that makes it able to easily communicate with youtube.. should be expanded in the future!
 *
 * @copyright 	oneDot only <we@onedotonly.be>
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */

class Youtube {


	/**
	 *	variables that are used within the class
	 */
	var $youtube_url = 'http://gdata.youtube.com/feeds/api/';



	/**
	 * 	ask json info about video
	 *
	 *	@param		integer, id of the vimeo video
	 *	@param		string, markup return language (standard json, could be xml)
	 *	@return		array
	 */
	function get_video( $id, $output = 'json' ) {
	
		$video	= json_decode ( file_get_contents( $this->youtube_url . 'videos/' . $id . '?alt=' . $output ));
		return $video->entry;
	
	} 



	/**
	 * 	youtube request for info about movie
	 *
	 * 	@param		integer, id of the video
	 * 	@param		string / array with values you want to get
	 *	@return		string / array (defined by what)
	 */
	function video_info ( $id, $what ) {
	
		// get video information
		$video 	= $this->get_video( $id );
		
		// check for array => multiple values
		if ( is_array ( $what )) {
			foreach ($what as $info) {
				$return[$info] = $video->$info;
			}
			return $return;
			
		// single value 
		} else {
			return $video->$what;
		}
	}


}

/** 
 * VIMEO CLASS
 *
 * This can be used to communicate with vimeo (http://vimeo.com)
 *
 * This is only the beginning of a vimeo class that makes it able to easily communicate with vimeo.. should be expanded in the future!
 *
 * @copyright 	oneDot only <we@onedotonly.be>
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */

class Vimeo {

	/**
	 *	variables that are used within the class
	 */
	var $vimeo_url	= 'http://vimeo.com/api/v2/';



	/**
	 * 	ask json info about video
	 *
	 *	@param		integer, id of the vimeo video
	 *	@param		string, markup return language (standard json, could be xml)
	 *	@return		array
	 */
	function get_video( $id, $output = 'json' ) {
	
		$video	= json_decode ( file_get_contents( $this->vimeo_url . 'video/' . $id . '.' . $output ));
		return $video[0];
	
	} 



	/**
	 * 	vimeo request for info about movie
	 *
	 * 	@param		integer, id of the video
	 * 	@param		string / array with values you want to get
	 *	@return		string / array (defined by what)
	 */
	function video_info ( $id, $what ) {
	
		// get video information
		$video 	= $this->get_video( $id );
		
		// check for array => multiple values
		if ( is_array ( $what )) {
			foreach ($what as $info) {
				$return[$info] = $video->$info;
			}
			return $return;
			
		// single value 
		} else {
			return $video->$what;
		}
	}
}


